//
//  OnlineTop-up.m
//  WanCaiC8
//
//  Created by tangang on 2018/3/28.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "OnlineTop_up.h"
#import "Top_upCell.h"
#import "Top_upPriceCell.h"
#import <AlipaySDK/AlipaySDK.h>
#import "MyVM.h"
@interface OnlineTop_up ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic ,strong) UITableView   *tableView;
@property (nonatomic ,strong) UIImageView   *payIcon;
@property (nonatomic ,strong) QXLable   *payName;
@property (nonatomic ,strong) UICollectionView *collectionView;
@property (nonatomic ,strong) UITextField       *payText;
@property (nonatomic ,strong) NSMutableArray    *priceArr;
@end

@implementation OnlineTop_up{
    NSInteger   selectPrice;
    NSInteger   selectType;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"在线充值";
    [self headView];
}

- (void)headView{
    UIView *headView=[[UIView alloc]init];
    headView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:headView];
    [headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(@128);
    }];
    
    _payIcon=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"pay_wechat"]];
    [headView addSubview:_payIcon];
    [_payIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headView).with.offset(10);
        make.top.equalTo(headView).with.offset(8);
        make.size.mas_equalTo(CGSizeMake(25, 25));
    }];
    
    _payName=[[QXLable alloc]initWithBFount:15];
    _payName.text=@"微信支付";
    [headView addSubview:_payName];
    [_payName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_payIcon.mas_right).with.offset(10);
        make.centerY.equalTo(_payIcon);
        make.size.mas_equalTo(CGSizeMake(100, 25));
    }];
    
    QXLable *labPrompt=[[QXLable alloc]initWithFount:10];
    labPrompt.text=@"兑换比例：1元=10金币";
    labPrompt.textColor=NAVCOLOR;
    labPrompt.textAlignment=NSTextAlignmentRight;
    [headView addSubview:labPrompt];
    [labPrompt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(headView).with.offset(-10);
        make.centerY.equalTo(_payIcon);
        make.size.mas_equalTo(CGSizeMake(120, 25));
    }];
    
    UIView *line=[[UIView alloc]init];
    line.backgroundColor=DEFAULTBGCOLOR;
    [headView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_payIcon.mas_bottom).with.offset(6);
        make.left.equalTo(_payIcon);
        make.right.equalTo(labPrompt);
        make.height.mas_equalTo(@.7);
    }];
    
    [headView addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headView).with.offset(25);
        make.right.equalTo(headView).with.offset(-25);
        make.top.equalTo(line).with.offset(8);
        make.height.mas_equalTo(@30);
    }];
    
    UIView *line1=[[UIView alloc]init];
    line1.backgroundColor=DEFAULTBGCOLOR;
    [headView addSubview:line1];
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.collectionView.mas_bottom).with.offset(6);
        make.left.equalTo(_payIcon);
        make.right.equalTo(labPrompt);
        make.height.mas_equalTo(@.7);
    }];
    
    QXLable *labTopUp=[[QXLable alloc]initWithFount:15];
    labTopUp.text=@"充值金额:";
    [headView addSubview:labTopUp];
    [labTopUp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.collectionView);
        make.top.equalTo(line1).with.offset(15);
    }];
    
    QXLable *labUnits=[[QXLable alloc]initWithFount:15];
    labUnits.text=@"元";
    labUnits.textAlignment=NSTextAlignmentRight;
    [headView addSubview:labUnits];
    [labUnits mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(labTopUp);
        make.right.equalTo(self.collectionView);
    }];
    
    _payText=[[UITextField alloc]init];
    _payText.text=@"20";
    _payText.keyboardType=UIKeyboardTypeNumberPad;
    _payText.font=[UIFont systemFontOfSize:15];
    _payText.textColor=DEFAULTTEXTBLACKCOLOR;
    _payText.placeholder=@"请输入充值金额";
    [headView addSubview:_payText];
    [_payText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(labTopUp);
        make.left.equalTo(labTopUp.mas_right);
        make.right.equalTo(labUnits.mas_left);
    }];
    
    UIButton  *btnTopUp=[[UIButton alloc]init];
    btnTopUp.backgroundColor=NAVCOLOR;
    btnTopUp.layer.masksToBounds=YES;
    btnTopUp.layer.cornerRadius=2;
    [btnTopUp addTarget:self action:@selector(onclickTopUp) forControlEvents:UIControlEventTouchUpInside];
    [btnTopUp setTitle:@"充值" forState:UIControlStateNormal];
    [self.view addSubview:btnTopUp];
    [btnTopUp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headView.mas_bottom).with.offset(15);
        make.left.equalTo(self.view).with.offset(35);
        make.right.equalTo(self.view).with.offset(-35);
        make.height.mas_equalTo(@38);
    }];
    
    [self.tableView reloadData];
}

#pragma mark --充值
- (void)onclickTopUp{
    
    if ([self.payText.text floatValue]==0) {
        [SVProgressHUD showErrorWithStatus:@"请输入充值金额"];
        return;
    }
    
    if (selectType==0) {
        [[MyVM manage] getWechatInfoWithMoney:[self.payText.text floatValue] andSuccess:^(id returnValue) {
            NSDictionary *dict=returnValue;
            PayReq *req = [[PayReq alloc] init];
            req.partnerId           = [dict objectForKey:@"MchId"];
            req.prepayId            = [dict objectForKey:@"PrepayId"];
            req.nonceStr            = [dict objectForKey:@"NonceStr"];
            NSMutableString *stamp  = [dict objectForKey:@"CreatedOn"];
            req.timeStamp           = (UInt32)[stamp longLongValue];
            req.package             = [dict objectForKey:@"Package"];
            req.sign                = [dict objectForKey:@"Sign"];
            [WXApi sendReq:req];
        } andFail:^(NSString *errorMessage, NSError *error) {
            
        }];
    }else{
        [[MyVM manage] getZfbInfoWithMoney:[self.payText.text floatValue] andSuccess:^(id returnValue) {
            NSString *ResponseBody=[returnValue objectForKey:@"ResponseBody"];
            [[AlipaySDK defaultService] payOrder:ResponseBody fromScheme:@"TicketPlan" callback:^(NSDictionary *resultDic) {
                NSLog(@"reslut = %@",resultDic);
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付结果" message:@"支付结果：成功！" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                
            }];
        } andFail:^(NSString *errorMessage, NSError *error) {
            
        }];
    }
    
    
}


#pragma mark -- UITableViewDelegate ,UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Top_upCell *cell=[tableView dequeueReusableCellWithIdentifier:@"Top_upCell" forIndexPath:indexPath];
    [cell setType:indexPath.row andIsSelect:indexPath.row==selectType];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        _payIcon.image=[UIImage imageNamed:@"pay_wechat"];
        _payName.text=@"微信支付";
    }else{
        _payIcon.image=[UIImage imageNamed:@"pay_alipay"];
        _payName.text=@"支付宝";
    }
    selectType=indexPath.row;
    [tableView reloadData];
}

#pragma mark - collectionView代理函数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.priceArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    Top_upPriceCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"Top_upPriceCell" forIndexPath:indexPath];
    [cell setTitle:self.priceArr[indexPath.row] andIsSelect:indexPath.row==selectPrice];
    return cell;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    selectPrice=indexPath.row;
    _payText.text=self.priceArr[indexPath.row];
    [collectionView reloadData];
}

#pragma mark -- 懒加载
- (UITableView *)tableView{
    if (!_tableView) {
        WS(weakSelf);
        _tableView=[[UITableView alloc]init];
        _tableView.dataSource=self;
        _tableView.delegate=self;
        _tableView.backgroundColor=DEFAULTBGCOLOR;
        _tableView.estimatedRowHeight=50;
        _tableView.rowHeight=UITableViewAutomaticDimension;
        [_tableView registerClass:[Top_upCell class] forCellReuseIdentifier:@"Top_upCell"];
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(weakSelf.view).with.insets(UIEdgeInsetsMake(200, 0, 0, 0));
        }];
    }
    return _tableView;
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        [layout setItemSize:CGSizeMake((SCREEN_WIDTH-50-28*3-1)/4.0, 30)];
        [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        layout.minimumInteritemSpacing = 0.0;
        layout.minimumLineSpacing = 28.0;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator=NO;
        [_collectionView registerClass:[Top_upPriceCell class] forCellWithReuseIdentifier:@"Top_upPriceCell"];
    }
    return _collectionView;
}


- (NSMutableArray *)priceArr{
    if (!_priceArr) {
        _priceArr=[[NSMutableArray alloc]initWithObjects:@"20",@"100",@"500",@"1000", nil];
    }
    return _priceArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
